#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
交易明细面板
"""

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTableWidget, 
                             QTableWidgetItem, QHeaderView, QPushButton, 
                             QDateEdit, QLabel, QComboBox)
from PyQt5.QtCore import QDate, Qt
from database import Database
import sqlite3


class TransactionWidget(QWidget):
    """交易明细面板"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
        self.load_data()
        
    def setup_ui(self):
        """设置界面"""
        layout = QVBoxLayout()
        
        # 顶部控制栏
        control_layout = QHBoxLayout()
        
        # 开始日期
        control_layout.addWidget(QLabel("开始日期:"))
        self.start_date = QDateEdit()
        self.start_date.setDate(QDate.currentDate().addMonths(-1))
        self.start_date.setDisplayFormat("yyyy-MM-dd")
        self.start_date.dateChanged.connect(self.load_data)
        control_layout.addWidget(self.start_date)
        
        # 结束日期
        control_layout.addWidget(QLabel("结束日期:"))
        self.end_date = QDateEdit()
        self.end_date.setDate(QDate.currentDate())
        self.end_date.setDisplayFormat("yyyy-MM-dd")
        self.end_date.dateChanged.connect(self.load_data)
        control_layout.addWidget(self.end_date)
        
        # 类型筛选
        control_layout.addWidget(QLabel("类型:"))
        self.type_combo = QComboBox()
        self.type_combo.addItems(["全部", "收入", "支出"])
        self.type_combo.currentTextChanged.connect(self.load_data)
        control_layout.addWidget(self.type_combo)
        
        # 分类筛选
        control_layout.addWidget(QLabel("分类:"))
        self.category_combo = QComboBox()
        self.category_combo.addItem("全部")
        self.category_combo.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        self.update_category_combo()
        self.category_combo.currentTextChanged.connect(self.load_data)
        control_layout.addWidget(self.category_combo)
        
        # 刷新按钮
        refresh_button = QPushButton("刷新")
        refresh_button.clicked.connect(self.load_data)
        control_layout.addWidget(refresh_button)
        
        control_layout.addStretch()
        layout.addLayout(control_layout)
        
        # 交易明细表格
        self.table = QTableWidget()
        self.table.setColumnCount(7)
        self.table.setHorizontalHeaderLabels(["时间", "类型", "金额", "分类", "对方", "来源", "备注"])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        layout.addWidget(self.table)
        
        self.setLayout(layout)
        
    def update_category_combo(self):
        """更新分类筛选下拉框"""
        # 只有在分类下拉框为空时才更新分类
        if self.category_combo.count() > 1:  # "全部"选项始终存在
            return
        
        # 获取数据库中所有出现的分类
        db = Database()
        conn = sqlite3.connect(db.db_path)
        cursor = conn.cursor()
        cursor.execute("SELECT DISTINCT category FROM transactions")
        categories = cursor.fetchall()
        conn.close()
        
        # 获取数据库中的分类
        db_categories = [cat[0] for cat in categories]
        
        # 处理分类显示，如果是一级|二级格式，只显示二级分类
        displayed_categories = set()  # 使用集合来避免重复
        for category in db_categories:
            if '|' in category:
                category_parts = category.split('|')
                if len(category_parts) >= 2 and category_parts[1]:
                    displayed_category = category_parts[1]
                else:
                    displayed_category = category_parts[0]
            else:
                displayed_category = category
            displayed_categories.add(displayed_category)
        
        # 批量添加分类到下拉框
        self.category_combo.addItems(list(displayed_categories))
    
    def load_data(self):
        """加载数据"""
        # 更新分类筛选下拉框
        self.update_category_combo()
        
        # 获取筛选条件
        start_date = self.start_date.date().toString("yyyy-MM-dd") + " 00:00:00"
        end_date = self.end_date.date().toString("yyyy-MM-dd") + " 23:59:59"
        type_filter = self.type_combo.currentText()
        category_filter = self.category_combo.currentText()
        
        # 查询数据库，根据类型筛选以提高性能
        db = Database()
        if type_filter != "全部":
            transactions = db.get_transactions(start_date, end_date, type_filter)
        else:
            transactions = db.get_transactions(start_date, end_date)
        
        # 根据分类筛选
        if category_filter != "全部":
            filtered_transactions = []
            for transaction in transactions:
                # 处理分类显示，如果是一级|二级格式，只显示二级分类
                category = transaction[4]
                if '|' in category:
                    category_parts = category.split('|')
                    if len(category_parts) >= 2 and category_parts[1]:
                        displayed_category = category_parts[1]
                    else:
                        displayed_category = category_parts[0]
                else:
                    displayed_category = category
                
                if displayed_category == category_filter:
                    filtered_transactions.append(transaction)
            transactions = filtered_transactions
        
        # 批量更新表格
        self.table.setRowCount(len(transactions))
        
        # 准备表格数据
        table_data = []
        for transaction in transactions:
            # transaction格式: (id, timestamp, amount, type, category, payee, source, note)
            row_data = [
                transaction[1],  # timestamp
                transaction[3],  # type
                f"¥{transaction[2]:.2f}",  # amount
            ]
            
            # 处理分类显示，如果是一级|二级格式，只显示二级分类
            category = transaction[4]
            if '|' in category:
                category_parts = category.split('|')
                if len(category_parts) >= 2 and category_parts[1]:
                    category = category_parts[1]
                else:
                    category = category_parts[0]
            row_data.append(category)  # category
            
            row_data.extend([
                transaction[5],  # payee
                transaction[6],  # source
                transaction[7]   # note
            ])
            
            table_data.append(row_data)
        
        # 批量设置表格项
        for row, row_data in enumerate(table_data):
            for col, data in enumerate(row_data):
                self.table.setItem(row, col, QTableWidgetItem(str(data) if data is not None else ""))
        
        # 调整列宽
        self.table.resizeColumnsToContents()